package org.shangrila.bme.mb;

/**
 * 使用Spring Controller Bean  注入DB
 *  
 */
import java.io.Serializable;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.primefaces.event.RowEditEvent;
import org.primefaces.event.TabChangeEvent;
import org.shangrila.bme.eo.BmeCustomer;
import org.shangrila.comm.dao.DbAccess;
import org.shangrila.comm.helper.IDHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.annotation.SessionScope;

@Controller
@SessionScope
public class CustomerController implements Serializable {
	private static final long serialVersionUID = -5951492023664217108L;
	private List<BmeCustomer> vo; //显示列表
    private BmeCustomer customer;
    private BmeCustomer selectedCustomer;

    @Autowired
    private DbAccess db;
    
    @PostConstruct
    public void init() {
    	newBmeCustomer();
    	vo = db.findEntityAll("BmeCustomer");
    }
         
    public void newBmeCustomer() {
    	customer = new BmeCustomer();
    	customer.setId(IDHelper.genStrIDs(16));
    }

    public void onTabChange(TabChangeEvent event) {
    	String tabid =  event.getTab().getId();    	
    	if("tab2".equals(tabid)) {    		

    	}
    }
    
	public String addAction() {
		
		db.beginTransaction();
		db.insert(customer);
		db.commitTransaction();
		
		showMessage("录入", "信息录入成功");
		
		vo.add(customer);
		newBmeCustomer();
		return null;
	}
      
    public void onRowEdit(RowEditEvent event) {
    	selectedCustomer = vo.get(vo.indexOf((BmeCustomer) event.getObject()));
    	db.beginTransaction();
    	db.update(selectedCustomer);
    	db.commitTransaction();
    	showMessage("编辑", "编辑保存成功。");
    }
     
    public void onRowCancel(RowEditEvent event) {
    	showMessage("编辑", "取消编辑成功。");
    }
    
	public void showMessage(String summary, String detail) {
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,summary, detail);
		FacesContext.getCurrentInstance().addMessage(null, message);
	}

    public List<BmeCustomer> getVo() {
		return vo;
	}

	public void setVo(List<BmeCustomer> vo) {
		this.vo = vo;
	}

	public BmeCustomer getCustomer() {
		return customer;
	}

	public void setCustomer(BmeCustomer customer) {
		this.customer = customer;
	}

	public BmeCustomer getSelectedCustomer() {
		return selectedCustomer;
	}

	public void setSelectedCustomer(BmeCustomer selectedCustomer) {
		this.selectedCustomer = selectedCustomer;
	}
}

